package com.itheima.travel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itheima.travel.enums.StatusEnum;
import com.itheima.travel.exception.ProjectException;
import com.itheima.travel.req.*;
import com.itheima.travel.res.GetwayRespons;
import com.itheima.travel.service.*;
import com.itheima.travel.session.SubjectSeller;
import com.itheima.travel.session.SubjectSellerContext;
import com.itheima.travel.session.SubjectUser;
import com.itheima.travel.session.SubjectUserContext;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.ExceptionsUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

@Service
@Log4j2
public class GatewayServiceImpl implements GatewayService {
    @Autowired
    private AffixService affixService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private FavoriteService favoriteService;
    @Autowired
    private UserService userService;
    @Autowired
    private RouteService routeService;
    @Autowired
    private SubjectSellerContext subjectSellerContext;
    @Autowired
    private SubjectUserContext subjectUserContext;

    //文件上传位置
    @Value("${upLoad.webSite}")
    private String webSite;

    //过滤方法
    @Override
    public GetwayRespons methods(String method, BaseRequest baseRequest, MultipartFile multipartFile) {
        //获取请求对象
        Object data = baseRequest.getData();
        //定义一个jsonString字符串
        String jsonString = null;
        if (!EmptyUtil.isNullOrEmpty(data)) {
            //如果获取的数据不是空，将其转为json
            jsonString = JSONObject.toJSONString(data);
        }
        //将字符串转为对象类型
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        //初始化响应信息
        GetwayRespons getwayRespons = new GetwayRespons();
        //获取商家对象
        SubjectSeller subjectSeller = subjectSellerContext.getSubject();
        //判断当前用户是否为商家类型
        if (!EmptyUtil.isNullOrEmpty(subjectSeller)) {
            //如果是不是空，则为商家
            //设置响应回去的信息id为该商家id
            getwayRespons.setUserId(subjectSeller.getId());
            //设置响应回去的名字为商家姓名
            getwayRespons.setUserName(subjectSeller.getSellerName());
        }
        //如果不是商家，则判断是否为用户
        SubjectUser subjectUser = subjectUserContext.getSubject();
        if (!EmptyUtil.isNullOrEmpty(subjectUser)) {
            //如果是用户，设置响应回去的id和名字
            getwayRespons.setUserId(subjectUser.getId());
            getwayRespons.setUserName(subjectUser.getUsername());
        }
        //如果都不是，则未登录状态，返回空
        //定义一个响应的返回数据，将信息存入进去，返回该对象即可
        Object dataResult = null;
        try {
            switch (method) {
                //根据方法名称，选择哪个方法确定执行
                case "currentSubjectUser":
                    dataResult = subjectUser;
                    break;
                case "currentSubjectSeller":
                    dataResult = subjectUser;
                    break;
                //文件上传
                case "upLoad":
                    dataResult = affixService.upLoad(multipartFile, JSONObject.toJavaObject(jsonObject, AffixVo.class));
                    break;
                //为上传的线路信息作业务绑定
                case "bindBusinessId":
                    dataResult = affixService.bindBusinessId(JSONObject.toJavaObject(jsonObject, AffixVo.class));
                    break;
                //根据业务id查询所有附件信息
                case "findAffixBuBusinessId":
                    dataResult = affixService.findAffixBuBusinessId(JSONObject.toJavaObject(jsonObject, AffixVo.class));
                    break;
                //注册用户信息
                case "registerUser":
                    dataResult = userService.registerUser(JSONObject.toJavaObject(jsonObject, UserVo.class));
                    break;
                //用户登录
                case "loginUser":
                    dataResult = userService.loginUser(JSONObject.toJavaObject(jsonObject, UserVo.class));
                    break;
                //登出
                case "loginOutUser":
                    userService.loginOutUser();
                    //登出成功
                    dataResult = true;
                    break;
                    //是否登录
                case "isLogin":
                    dataResult=userService.isLogin();
                    break;
                    //查询所有的分类信息
                case "findAllCategory":
                    dataResult=categoryService.findAllCategory();
                    break;
                    //是否收藏过
                case "isFavorite":
                    dataResult=favoriteService.isFavorite(JSONObject.toJavaObject(jsonObject,FavoriteVo.class));
                    break;
                    //添加收藏
                case "addFavorite":
                    dataResult=favoriteService.addFavorite(JSONObject.toJavaObject(jsonObject,FavoriteVo.class));
                    break;
                    //查询收藏
                case "findMyFavorite":
                    dataResult=favoriteService.findMyFavorite(JSONObject.toJavaObject(jsonObject,FavoriteVo.class),baseRequest.getPageNum(),baseRequest.getPageSize());
                    break;
                    //添加线路信息
                case "addRoute":
                    dataResult=routeService.addRoute(JSONObject.toJavaObject(jsonObject, RouteVo.class));
                    break;
                    //根据id查询线路信息
                case "findRouteById":
                    dataResult=routeService.findRouteById(JSONObject.toJavaObject(jsonObject,RouteVo.class));
                    break;
                    //分页查询路线
                case "findRouteByPage":
                    dataResult=routeService.findRouteByPage(JSONObject.toJavaObject(jsonObject,RouteVo.class),baseRequest.getPageNum(),baseRequest.getPageSize());
                    break;
                    //如果方法名对不上，则走该情况
                default:
                    log.error("调用：{}接口：不合法",method);
                    getwayRespons = error(getwayRespons,new ProjectException("1010","请求不合法"));
                    break;
            }
            //返回处理
            buildGetwayRespons(getwayRespons,dataResult, StatusEnum.SUCCEED.getCode(),StatusEnum.SUCCEED.getMsg());
        } catch (Exception e) {
            log.error("调用：{}接口出错：{}",method,
                    ExceptionsUtil.getStackTraceAsString(e));
            //将错误信息带回去
            getwayRespons=error(getwayRespons,e);
        }
        return getwayRespons;
    }

    private GetwayRespons buildGetwayRespons(GetwayRespons getwayRespons, Object dataResult, String code, String msg) {
        //设置响应带回去的数据
        getwayRespons.setData(dataResult);
        //响应状态码
        getwayRespons.setCode(code);
        //响应信息
        getwayRespons.setMsg(msg);
        //操作时间
        getwayRespons.setOperationTime(new Date());
        //文件下载地址
        getwayRespons.setWebSite(webSite);
        //将结果返回
        return getwayRespons;

    }

    @Override
    public GetwayRespons error(GetwayRespons respons, Exception e) {
       //异常处理
        ProjectException projectException=null;
        if(e instanceof ProjectException){
            //异常类型属于ProjectException类型
            //转换异常类型，处理异常
            projectException = (ProjectException) e;
        }else {
            //否则响应错误信息
            projectException= new ProjectException(StatusEnum.FAIL.getCode(),StatusEnum.FAIL.getMsg());
        }
        //返回错误信息
        return buildGetwayRespons(respons,null,projectException.getCode(),projectException.getMessage());
    }
}
